# 启动 停止 jar 的脚本
#!/bin/bash
MYSQL_PW_DM_V=aaa123;
export MYSQL_PW_DM_V

FILEDIR=/home/zzy
JAVA_HOME=/home/javasoft/jdk1.8.0_162/bin


PROXY_ENABLE=false

APPNAME=test
PIDFILE=/var/run/${APPNAME}.pid
FILEPATH=${FILEDIR}/${APPNAME}.jar
APPLICATION=${FILEDIR}/application.properties

PROXY_PATH=${FILEDIR}/bin/proxychain4
PROXY_CONFIG=${FILEDIR}/bin/proxychains.conf

JAVA_OPTS="-Xms1024m -Xmx1024m"
JAVA=$JAVA_HOME/java


# chmod +x PROXY_PATH

start(){
  process_stat
  STAT=$?
  if [ $STAT -eq 0 ] ; then
	echo "${APPNAME} is already running"
	return $STAT
  elif [ $STAT -eq 1 ] ; then
	echo -n "Start  ${APPNAME} :"
 if  [ $PROXY_ENABLE = true ] ; then
	echo -n "proxy enable: true"
    # MYSQL_PW_DM_V = `sh ./decrypt.sh ${MYSQL_PW_DM_V }`
	nohup ${PROXY_PATH} -f   ${PROXY_CONFIG}  $JAVA   -jar $JAVA_OPTS  ${FILEPATH}  -Dspring.config.location=${APPLICATION}  --spring.datasource.password=${MYSQL_PW_DM_V} >/dev/null 2>&1 &
 else
	# echo -n "proxy enable: false"
   #MYSQL_PW_DM_V = `sh ./decrypt.sh ${MYSQL_PW_DM_V }`
    	 # nohup $JAVA -jar $JAVA_OPTS  ${FILEPATH}  -Dspring.config.location=${APPLICATION} --spring.datasource.password=${MYSQL_PW_DM_V} >/dev/null 2>&1 &

		# nohup $JAVA -jar $JAVA_OPTS  ${FILEPATH} >/dev/null 2>&1 &
		# 此方法解决 jeknis 不执行 nohup的问题
		echo "java -jar /root/.jenkins/workspace/PipelineTest/target/zzyboot-1.0.jar" | at now
 fi
 echo -n "[ok]"
 echo -n  "$(date): ${APPNAME} start success "
 fi
 # process_stat


}


stop(){
 flag=1
 process_stat
 while [ $? -eq "0" ]
    do
        if [ $flag -eq "1" ]; then
            kill -15 $pid
            echo "${APPNAME} is starting to stop ....."
            flag=$( expr $flag + 1)
            sleep 2  #wait 2 second
        elif [ $flag -eq "5" ]; then
            kill -9 $pid
            # fi
        else
            flag=$( expr $flag + 1)
            sleep 2  # wait 2 second
        fi
 process_stat
 done

  echo "${APPNAME} is stoped ."

 return 0

}


status (){
    process_stat
    STAT=$?
    if [ $STAT -eq 0 ] ; then
        echo "${APPNAME} is running"
        return $STAT
    elif [ $STAT -eq 1 ] ; then
        echo "${APPNAME} is stop"
        return $STAT
    fi
}

process_stat(){
   pid=`ps -ef |grep ${APPNAME} |grep -v grep|grep java |awk -F" " '{print $2}'`
   if [ -z "${pid}" ]; then
		# echo "application pid is null "
        return 1
    else
		echo "application ${APPNAME} pid is ${pid}"
        return 0
    fi
}

case "$1" in
start)
   start
;;
stop)
   stop
;;
restart)
   stop
   start
   echo ''
   status
;;
status)
   status
;;
*)
   printf ' Usage: %s {start|stop|restart|status}\n' "${APPNAME}"
   exit 1
   ;;
esac






